﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace GestorDeFlotasDesktop.AbmUsuario
{
    public partial class AbmUsuario : Form
    {
        private Modelo.FormActions.Actions action = Modelo.FormActions.Actions.Alta;
        private int selected_elem = -1;

        public AbmUsuario(Modelo.FormActions.Actions runAction, int id)
        {
            InitializeComponent();
            switch (runAction)
            {
                case Modelo.FormActions.Actions.Baja:
                    selected_elem = id;
                    this.loadData(selected_elem);
                    action = Modelo.FormActions.Actions.Baja;
                    tb_usuario.Enabled = false;
                    tb_passwd.Enabled = false;
                    cb_hab.Enabled = false;
                    dataGridView1.Enabled = false;
                    aceptar.Text = "Eliminar";
                    break;
                case Modelo.FormActions.Actions.Modificacion:
                    selected_elem = id;
                    this.loadData(selected_elem);
                    action = Modelo.FormActions.Actions.Modificacion;
                    tb_usuario.Enabled = false;
                    cb_hab.Enabled = false;
                    aceptar.Text = "Modificar";
                    break;
            }

        }

        public AbmUsuario(Modelo.FormActions.Actions runAction)
        {
            InitializeComponent();
            cb_hab.Enabled = false;
            using (SqlConnection con = Modelo.Modelo.createConnection())
            {
                SqlDataAdapter da = new SqlDataAdapter(Modelo.SqlQueries.getRoles, con);
                DataTable dt = new DataTable();
                da.Fill(dt);
                dataGridView1.DataSource = dt;
            }
        }

        private void loadData(int id)
        {
            using (SqlConnection con = Modelo.Modelo.createConnection())
            {
                SqlDataAdapter da = new SqlDataAdapter(Modelo.SqlQueries.getUserById(selected_elem), con);
                DataTable dt = new DataTable();
                da.Fill(dt);
                DataRow user_info = dt.Rows[0];
                tb_usuario.Text = user_info.ItemArray[1].ToString();
                cb_hab.Checked = (bool) user_info.ItemArray[2];


                SqlDataAdapter us_rol_da = new SqlDataAdapter(Modelo.SqlQueries.getUserRoles(selected_elem), con);
                DataTable us_rol_dt = new DataTable();
                us_rol_da.Fill(us_rol_dt);
                dataGridView1.DataSource = us_rol_dt;

            }
        }

        private void aceptar_Click(object sender, EventArgs e)
        {
            switch (action)
            {
                case Modelo.FormActions.Actions.Alta:
                    string error_txt = "ERROR: ";
                    if (String.IsNullOrEmpty(tb_usuario.Text))
                    {
                        error_txt = String.Concat(error_txt, "\n Nombre de usuario es obligatorio");
                    }
                    if (String.IsNullOrEmpty(tb_passwd.Text))
                    {
                        error_txt = String.Concat(error_txt, "\n Password es obligatorio");
                    }
                    if(!String.IsNullOrEmpty(tb_usuario.Text) && (!String.IsNullOrEmpty(tb_passwd.Text))){
                        using (SqlConnection con_un = Modelo.Modelo.createConnection())
                        {
                            try
                            {
                                Modelo.Modelo.openConnection(con_un);
                                SqlCommand comando_check_unique = new SqlCommand(Modelo.SqlQueries.getUserIdByUsername(tb_usuario.Text), con_un);
                                SqlDataReader reader = comando_check_unique.ExecuteReader();
                                if (reader.Read()) {
                                    MessageBox.Show("Usuario duplicado");
                                    break;
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                        }
                        using (SqlConnection con = Modelo.Modelo.createConnection())
                        {
                            try
                            {
                                Modelo.Modelo.openConnection(con);
                                SqlCommand comando_add_user = new SqlCommand(Modelo.SqlQueries.addUser(tb_usuario.Text, Login.Login.getSHA256(tb_passwd.Text)), con);
                                comando_add_user.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                        }
                        using (SqlConnection con2 = Modelo.Modelo.createConnection())
                        {
                            try
                            {
                                Modelo.Modelo.openConnection(con2);
                                SqlCommand comando_get_user_id = new SqlCommand(Modelo.SqlQueries.getUserIdByUsername(tb_usuario.Text), con2);
                                SqlDataReader reader = comando_get_user_id.ExecuteReader();
                                List<int> roles = new List<int>();
                                while (reader.Read())
                                {
                                    foreach (DataGridViewRow row in dataGridView1.Rows)
                                    {
                                        if (row.Cells["Added"].Value != null && Convert.ToInt32(row.Cells["Added"].Value) == 1)
                                        {
                                            roles.Add(Convert.ToInt32(row.Cells["Id"].Value));
                                        }
                                    }
                                    if (roles.Count > 0)
                                    {
                                        SqlConnection con3 = Modelo.Modelo.createConnection();
                                        Modelo.Modelo.openConnection(con3);
                                        SqlCommand comando_add_user_role = new SqlCommand(Modelo.SqlQueries.addUserRoles(Convert.ToInt32(reader.GetDecimal(0)), roles), con3);
                                        comando_add_user_role.ExecuteNonQuery();
                                        Modelo.Modelo.closeConnection(con3);
                                    }
                                }

                                MessageBox.Show(String.Format("Usuario {0} agregado", tb_usuario.Text));
                                Login.Login.mainForm.openForm(new AbmUsuario(Modelo.FormActions.Actions.Alta));
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                        }
                    } else {
                        MessageBox.Show(error_txt);
                    }
                    break;
                case Modelo.FormActions.Actions.Baja:
                    using (SqlConnection con = Modelo.Modelo.createConnection())
                    {
                        try
                        {
                            Modelo.Modelo.openConnection(con);
                            SqlCommand comando = new SqlCommand(Modelo.SqlQueries.deleteUser(selected_elem), con);
                            comando.ExecuteNonQuery();
                            MessageBox.Show(String.Format("Usuario {0} eliminado", tb_usuario.Text));
                            Login.Login.mainForm.openForm(new AbmUsuario(Modelo.FormActions.Actions.Alta));
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                    }
                    break;
                case Modelo.FormActions.Actions.Modificacion:
                    if (String.IsNullOrEmpty(tb_usuario.Text))
                    {
                        MessageBox.Show("Nombre de usuario es obligatorio");
                    }
                    else
                    {
                        List<int> roles_list = new List<int>();
                        foreach (DataGridViewRow row in dataGridView1.Rows)
                        {
                            if (row.Cells["Added"].Value != null && Convert.ToInt32(row.Cells["Added"].Value) == 1)
                            {
                                roles_list.Add(Convert.ToInt32(row.Cells["Id"].Value));
                            }
                        }
                        using (SqlConnection connection = Modelo.Modelo.createConnection())
                        {
                            try
                            {
                                Modelo.Modelo.openConnection(connection);
                                SqlCommand comando = new SqlCommand(Modelo.SqlQueries.updateUser(selected_elem, Login.Login.getSHA256(tb_passwd.Text), roles_list), connection);
                                comando.ExecuteNonQuery();
                                MessageBox.Show(String.Format("Usuario {0} modificado", tb_usuario.Text));
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                        }
                    }
                    break;
            }
        }
    }
}
